package com.hex.ds.hdrs.engine.interceptor;

import com.hex.bigdata.hbda.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Package: com.hex.dataService.hdrs.scheduleService.interceptor
 * @ClassName CheckInterceptor
 * @Description:验证特殊字符拦截器
 * @Author: <gc.zuo>
 * @Date 2021/6/8 9:01
 * @Version v1.0
 **/
@Slf4j
public class CheckInterceptor extends HandlerInterceptorAdapter {


    @Value("${check.specialCharacter}")
    private String specialCharacter;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        try {
            RequestWrapper requestWrapper = new RequestWrapper(httpServletRequest);
            String body = requestWrapper.getBody();
            boolean flag = true;
            if (StringUtils.isNotBlank(body)) {
                body = body.replace("\"", "");
                String[] character = specialCharacter.split(",");
                for (int i = 0; i < character.length; i++) {
                    if (body.contains(character[i])) {
                        //表示请求包含特殊字符
                        flag = false;
                        break;
                    }
                }
            }
            if (flag) {
                return true;
            }
        } catch (Exception e) {
            log.error("拦截器异常: {}", e.getMessage());
        }
        throw new Exception("输入存在特殊字符");
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}